/* eslint-disable space-before-function-paren */
/*
 * @Author: Aaron
 * @Date: 2022-03-01 11:18:12
 * @LastEditTime: 2022-11-08 17:51:25
 * @LastEditors: YanMeng
 * @Description: file content
 * @FilePath: \ias_ui\src\views\coi\spuChannelInventory\js\requestMixins.js
 * @Company: 沃尔玛
 */

import moment from 'moment'
import {
  getAlohaSpuByChannelList,
  downloadWares,
  getAlohaSpuAllList,
  spuDownloadWares,
  releaseChannel,
  handleLog,
  initChgSpu,
  batchUpdateShopCategoryByChannel as submitFun,
  handleLogTos
} from '@/api/coi/onlineTaskAPI/spuEdit.js'
import { stringToArray } from '@/utils/processingData'
import { queryTreeList, queryChannelTreeList } from '@/api/coi/onlineTaskAPI/sku'
import bus from '@/utils/eventBus.js'
import { filterKey } from '@/utils/processingData.js'
import { releaseStatus } from '@/views/coi/commonJs/dictionary.js'
import { operationLogTableHeader, operationLogTableHeaderList } from '@/views/coi/commonJs/spuWarehouseTableHead'
import { arrayToString } from '@/utils/processingData.js'

export const requestTableDataFun = {
  created() {
    this.requestData()
  },
  methods: {
    handleData() {
      const searchData = JSON.parse(JSON.stringify(this.searchData))
      if ('skuCodeList' in searchData) searchData.skuCodeList = stringToArray(searchData.skuCodeList, /[\n\r]/) // upc
      if ('channelSpuIdList' in searchData) searchData.channelSpuIdList = stringToArray(searchData.channelSpuIdList, /[\n\r]/) // 商品编号
      if ('categoryId' in searchData) searchData.categoryId = searchData.categoryId[searchData.categoryId.length - 1] - 0
      if ('shopCategoryId' in searchData) searchData.shopCategoryId = searchData.shopCategoryId[searchData.shopCategoryId.length - 1] - 0
      return searchData
    },
    changeLoading(v = true) {
      bus.$emit('changeLoading', v)
    },
    async requestData(v = this.pageParams) {
      try {
        this.changeLoading(true)
        let params = { ...this.handleData(), channelId: this.channelId, ...v }
        // 新的沃选spu内容则处理传参
        if (!window.appConfig.hiddenNewProducts) {
          const param = JSON.parse(JSON.stringify(params))
          params = {
            page: params.pageNum,
            size: params.pageSize,
            param
          }
          param.skuUpcWoCd = param.skuCodeList
          param.spuName = param.channelSpuName
          delete param.channelSpuName
          delete param.skuCodeList
          delete param.pageNum
          delete param.pageSize
        }
        const {
          result: { total, totalSize, records, spuChannelInfoRespList },
          code
        } = await getAlohaSpuByChannelList(params)
        if (code !== '0') return
        const list = window.appConfig.hiddenNewProducts ? spuChannelInfoRespList : records
        this.total = window.appConfig.hiddenNewProducts ? totalSize : total || 0
        list?.forEach((_) => {
          if (Array.isArray(_.shopCategoryName)) {
            _.shopCategoryName = window.appConfig.hiddenNewProducts ? arrayToString(_.shopCategoryName, ',', 'shopCategoryName') : _.shopCategoryName.join(',')
          }
          // todo spu新的跟旧的字段不一致 特殊化处理
          if (window.appConfig.hiddenNewProducts) {
            _.skuCount = _.skuSize
            _.upc = _.upcNbrList
          }
          if (Array.isArray(_.upc)) _.upcNbrListString = _.upc.map((_) => _.substring(0, 12)).join()
          if (_.hasOwnProperty('lastPushResult') && _.lastPushResult !== 0 && !_.lastPushResult) {
            _.lastPushResult = '1'
          }
          _.lastPushResult = filterKey(_.lastPushResult, releaseStatus)
          if (_.updateTime) _.updateTime = moment(_.updateTime).format('YYYY-MM-DD HH:mm:ss')
        })
        this.dataList = list || []
      } finally {
        this.changeLoading(false)
      }
    },
    async handleDownload(name) {
      try {
        this.changeLoading(true)
        const date = moment(new Date()).format('YYYY-MM-DD')
        if (!window.appConfig.hiddenNewProducts) {
          let params = { ...this.handleData(), channelId: this.channelId, ...this.pageParams }
          const param = JSON.parse(JSON.stringify(params))
          params = {
            page: params.pageNum,
            size: params.pageSize,
            param
          }
          param.skuUpcWoCd = param.skuCodeList
          param.spuName = param.channelSpuName
          delete param.channelSpuName
          delete param.skuCodeList
          delete param.pageNum
          delete param.pageSize
          delete param.channelBrandId
          await downloadWares(params, `${name} ${date}`)
        } else {
          await downloadWares({ ...this.handleData(), ...this.pageParams, channelId: this.channelId }, `${name} ${date}`)
        }
      } finally {
        this.changeLoading(false)
      }
    },
    async releaseChannelRequest(idList) {
      const { result } = await releaseChannel(idList)
      if (!result) return
      this.$message({
        type: 'success',
        message: '发布渠道成功！'
      })
    }
  }
}

export const serialInventoryTableFun = {
  created() {
    this.requestData()
  },
  methods: {
    handleData() {
      const searchData = JSON.parse(JSON.stringify(this.searchData))
      if ('skuCodeList' in searchData) searchData.skuCodeList = stringToArray(searchData.skuCodeList, /[\n\r]/)
      return searchData
    },
    changeLoading(v = true) {
      this.loading = v
    },
    async requestData(v = this.pageParams) {
      try {
        this.changeLoading(true)
        const { result } = await getAlohaSpuAllList({ ...this.handleData(), ...v })
        if (!result) return
        this.total = result.totalSize
        if (Array.isArray(result.spuChannelInfoRespList)) {
          result.spuChannelInfoRespList.forEach((_) => {
            if (_.updateTime) _.updateTime = moment(_.updateTime).format('YYYY-MM-DD HH:mm:ss')
          })
        }
        this.dataList = result.spuChannelInfoRespList || []
      } finally {
        this.changeLoading(false)
      }
    },
    async handleDownload(name) {
      try {
        this.changeLoading(true)
        const date = moment(new Date()).format('YYYY-MM-DD')
        await spuDownloadWares({ ...this.handleData(), ...this.pageParams }, `${name} ${date}`)
      } finally {
        this.changeLoading(false)
      }
    }
  }
}

export const getCategoryOptions = {
  methods: {
    async getChannelTreeList(channelId) {
      const { result } = await queryChannelTreeList({ channelId })
      if (!Array.isArray(result)) return
      this.options.categoryId = result
    },
    async getChannelShopTreeList(channelId) {
      const { result } = await queryTreeList({ channelId })
      if (!Array.isArray(result)) return
      this.options.shopCategoryId = result
    }
  }
}

export const getLogs = {
  data() {
    return {
      title: '操作日志',
      logVisible: false,
      operationLogTableHeader,
      operationLogTableHeaderList,
      operationLogTableList: []
    }
  },
  methods: {
    /**
     *
     * @param {*a是形参，接收表格行抛出的参数} a
     */
    async operationLog(a) {
      const obj = { spuCode: a.row.spuCode }
      // Todo 旧的日志接口是需要渠道id的 且判断了用不同的api
      if (this.channelId && window.appConfig.hiddenNewProducts) obj.channelId = this.channelId
      const { result } = window.appConfig.hiddenNewProducts ? await handleLog(obj) : await handleLogTos(obj)
      if (result && Array.isArray(result) && result.length) {
        result.forEach((_) => {
          if (_.updateTime) _.updateTime = moment(_.updateTime).format('YYYY-MM-DD HH:mm:ss')
        })
        this.operationLogTableList = result
        this.logVisible = true
      } else {
        this.$message.error('暂无操作日志')
      }
    }
  }
}

export const handleEditMinxin = {
  methods: {
    async handleEdit({ row }) {
      // debugger
      const spuCode = row.spuCode
      const createType = row.createType ? row.createType : 2
      console.log('********', row)
      if (!spuCode || !createType) return
      if (createType === 1) {
        if (!row.upcNbrList[0]) return
        bus.$emit('setTagName', row.channelSpuName)
        this.$router.push({
          path: `/commodityM/commodityEdit/${row.upcNbrList[0]}/edit/${this.$route.name}/06`,
          query: { tab: this.menuName }
        })
      } else if (createType === 2) {
        const { result } = await initChgSpu({ spuCode }, this.menuName)
        if (!result) return
        const query = {}
        if (this.menuName) {
          query.menuName = this.menuName
          query.spuCode = result || ' '
        }
        bus.$emit('setTagName', row.spuName)
        this.$router.push({
          path: `/SpuSeriesMaintain/${result}/all/${this.$route.name}`,
          query
        })
      }
    }
  }
}

export const spuDetail = {
  props: {
    menuName: {
      type: String,
      default: ''
    }
  },
  methods: {
    async goSpu(row) {
      console.log('reow', row)
      // const { result } = await initChgSpu({spuCode: row.spuCode }, this.menuName)
      // if (!result) return
      const query = {}
      if (this.menuName) {
        query.menuName = this.menuName
        query.spuCode = row.spuCode
        query.seeData = 'seeData'
        query.isModify = 'not'
      }
      bus.$emit('setTagName', row.channelSpuName || row.spuName)
      this.$router.push({
        path: `/spuSeries/${row.spuCode}/details/${this.$route.name}`,
        query
      })
    },
    goSku(row) {
      if (!row.upcNbrList[0]) return
      bus.$emit('setTagName', row.channelSpuName || row.spuName)
      this.$router.push({
        path: `/commodityM/commodityEdit/${row.upcNbrList[0]}/detail/${this.$route.name}/06`
      })
    },
    goSpuDetails({ row }) {
      const createType = row.createType
      if (createType === 1) this.goSku(row)
      else this.goSpu(row)
    }
  }
}

export const modifyCategoryFun = {
  data() {
    return {
      submitFun,
      categoryVisible: false,
      skuCodeList: []
    }
  },
  methods: {
    onCategoryEdit() {
      const idList = this.checkQuantity(false, 50)
      if (!idList) return
      this.skuCodeList = idList.map((_) => _.spuCode)
      this.categoryVisible = true
    }
  }
}
